import FileSaver from "file-saver";
import * as XLSX from "xlsx";

// 将页面的table表格导出为Excel表格
/**
 * @function htmlToExcel 将页面的table表格导出为Excel表格
 * @param htmlId    tableId --- 页面table表格的id, 默认值为"#table"
 * @param   String   title --- 导出的文件的名字,m默认值为 “html”
 */
export function htmlToExcel(tableId = "#table", title = "html") {
	// 导出当前表格
	var wb = XLSX.utils.table_to_book(document.querySelector(tableId)); //表格id
	var wbout = XLSX.write(wb, {
		bookType: "xlsx",
		bookSST: true,
		type: "array",
	});
	try {
		FileSaver.saveAs(
			new Blob([wbout], { type: "application/octet-stream" }),
			title + ".xlsx"
		); //文件名
	} catch (e) {
		if (typeof console !== "undefined") console.log(e, wbout);
	}
	return wbout;
}

// 将二维数组导出为Excel表格
/**
 * @function dataToExcel --- 将二维数组导出为Excel表格
 * @param Array data --- 必须是一个二维数组
 * @param String    title --- 导出的文件的名字, 默认值为"data"
 */
export function dataToExcel(data = [], title = "data") {
	const wb = XLSX.utils.book_new();
	const ws = XLSX.utils.aoa_to_sheet(data);
	XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
	var wbout = XLSX.write(wb, {
		bookType: "xlsx",
		bookSST: true,
		type: "array",
	});
	try {
		FileSaver.saveAs(
			new Blob([wbout], { type: "application/octet-stream" }),
			title + ".xlsx"
		); //文件名
	} catch (e) {
		if (typeof console !== "undefined") console.log(e, wbout);
	}
}
